
import socket
import configparser
import os
import logging
import datetime

#变量值管理类
#方便储存跨作用域变量
#(注:我知道写的很烂,时间原因,望谅解)
class ValueManager:
    def __init__(self):
        self.Value={}
    def addValue(self,key, value):
        self.Value[key]=value
    def getValue(self,key):
        return self.Value[key]
    def deleteValue(self,key):
        del self.Value[key]

#暂无需求,无需开发
class LangModule:
    def __init__(self):
        pass

class LogManager:
    def __init__(self):
        logging.basicConfig(level=logging.DEBUG)
        logging.info("日志系统初加载完成!")
    def reload(self,value:ValueManager):
        logging.info("日志系统开始深度加载!")
        _level=value.getValue("Logging_Level")
        if(_level=="DEBUG"):
            logging.info("日志等级设置为:DEBUG")
            del _level
            _level=logging.DEBUG
        elif(_level=="INFO"):
            logging.info("日志等级设置为:INFO")
            del _level
            _level=logging.INFO
        elif(_level=="WARNING"):
            logging.info("日志等级设置为:WARNING")
            del _level
            _level=logging.WARNING
        elif(_level=="ERROR"):
            logging.info("日志等级设置为:ERROR")
            del _level
            _level=logging.ERROR
        elif (_level=="CRITICAL"):
            logging.info("日志等级设置为:CRITICAL")
            del _level
            _level=logging.CRITICAL
        else:
            logging.warning("未知日志等级设置,自动切换为[DEBUG]")
        # 创建logs文件夹（如果不存在）
        if not os.path.exists('logs'):
            os.makedirs('logs')

        # 获取当前日期
        current_date = datetime.datetime.now().strftime('%Y-%m-%d')

        # 设置日志文件路径
        log_file = f'logs/{current_date}.log'

        # 创建logger对象
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # 创建文件处理器
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)

        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)

        # 创建日志格式器
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # 将格式器添加到处理器
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 将处理器添加到logger对象
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        
        logging.info(f"日志系统深度加载成功,日志文件写入开始,文件为: ./{log_file}")

#配置文件读取程序
class ConfigModule:
    def __init__(self,filename="Settings.conf"):
        self.file=None
        if(os.path.exists(filename)==False):
            logging.error("配置文件不存在!")
            self.notExistFunc(filename)
        self.filename = filename
        self.conf = configparser.ConfigParser(allow_no_value=True)
        self.conf.read(self.filename)
        self.file = open(self.filename, 'w')
        logging.info("配置文件读取完成")

    def getKey(self,section,key):
        return self.conf[section][key]
    def getSection(self,section):
        return self.conf[section]
    def setValue(self,section,key,value):
        if(self.conf.has_section(section)==False):
            self.conf[section]={}
        self.conf[section][key] = value
    def setSection(self,section):
        self.conf[section]={}
    def delKey(self,section,key):
        self.conf.remove_option(section,key)
    def delSection(self,section):
        self.conf.remove_section(section)
    def isKeyExist(self,section,key):
        if(self.conf.has_option(section,key)):
            return True
        else:
            return False
    def isSectionExist(self,section):
        if(self.conf.has_section(section)):
            return True
        else:
            return False
    def WriteCaching(self):
        self.conf.write(self.file)
    def notExistFunc(self,filename):
        open(filename, 'w')
        logging.info("创建配置文件成功")

#网络类
class SocketModule:
    def __init__(self):
        logging.info("网络通讯开始加载!")

#潜水艇控制程序
#提供接口交给网络类管理
class CtrlModule:
    def __init__(self):
        logging.info("控制程序开始加载!")

#初始化服务器设置,如需添加,按格式处理
def InitSettings(config:ConfigModule):
    #服务器设置
    config.setValue("Settings","RunMode","Ctrl")
    #日志等级设置
    config.setValue("Logging","Level","DEBUG")
    #网络连接设置
    config.setValue("NetWork","Host","127.0.0.1")
    config.setValue("NetWork","Port","1029")
    
#服务器设置读取,如需添加,按格式处理
#将文件存储在Value里,无需在使用时再次读取,热更改服务器配置ReLoad需要重新运行该程序
def ReadSetting(config:ConfigModule,value:ValueManager):
    #服务器设置
    value.addValue("Setting_RunMode",config.getKey("Settings","RunMode"))
    #日志等级
    value.addValue("Logging_Level",config.getKey("Logging","Level"))
    #网络连接
    value.addValue("NetWork_Host",config.getKey("NetWork","Host"))
    value.addValue("NetWork_Port",config.getKey("NetWork","Port"))

if __name__ == '__main__':
    logger = LogManager()
    logging.info("程序正在启动中...")
    value=ValueManager()
    MainConfig = ConfigModule("Settings.conf")
    if(MainConfig.isSectionExist("Settings")==False):
        InitSettings(MainConfig)
        MainConfig.WriteCaching()
    ReadSetting(MainConfig,value)
    logger.reload(value)
    ctrlModule = CtrlModule()